#pragma once
#include <iostream>
#include <queue>
#include <vector>
#include <pthread.h>
#include <semaphore.h>
const static int default_cap = 5;

template <typename T>
class RingQueue
{
public:
    RingQueue(unsigned int cap = default_cap)
        : _cap(cap), _ringqueue(cap), _blank_step(0), _data_step(0)
    {
        sem_init(&_p_sem, 0, _cap);
        sem_init(&_c_sem, 0, 0);
    }

    void Equeue(const T &in)
    {
        sem_wait(&_p_sem);
        {
            pthread_mutex_lock(&_p_mutex);
            _ringqueue[_blank_step] = in;
            _blank_step++;
            _blank_step %= _cap;
            pthread_mutex_unlock(&_p_mutex);
        }
        sem_post(&_c_sem);
    }

    T Pop()
    {
        T result;
        sem_wait(&_c_sem);
        {
            pthread_mutex_lock(&_c_mutex);
            result = _ringqueue[_data_step];
            _data_step++;
            _data_step %= _cap;
            pthread_mutex_unlock(&_c_mutex);
        }
        sem_post(&_p_sem);

        return result;
    }
    ~RingQueue()
    {
        sem_destroy(&_c_sem);
        sem_destroy(&_p_sem);
    }

private:
    std::vector<T> _ringqueue;
    unsigned int _cap;
    sem_t _p_sem;
    unsigned int _blank_step;
    pthread_mutex_t _p_mutex;
    sem_t _c_sem;
    unsigned int _data_step;
    pthread_mutex_t _c_mutex;
};